package com.stenio.fancat.service.shop;

import com.stenio.fancat.domain.shop.FcShopImage;
import com.stenio.fancat.domain.shop.FcVenderImage;
import com.stenio.fancat.mapper.shop.FcVenderImageMapper;
import com.stenio.fancat.service.OssService;
import com.stenio.fancat.service.enums.ImageType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author liuan
 * @create 2019-01-16 15:10
 */
@Service
public class VenderImageService {

    @Autowired
    private FcVenderImageMapper fcVenderImageMapper;

    @Autowired
    private OssService ossService;

    @Value("${oss.piggybank.endpoint}")
    private String piggybankEndPoint;

    private static final Logger logger = LoggerFactory.getLogger(VenderImageService.class);

    public FcVenderImage findById(Integer id) {
        return fcVenderImageMapper.findById(id);
    }

    /**
     * 保存图片
     * @param file
     * @return
     */
    public FcVenderImage saveImage(MultipartFile file){
        FcVenderImage image = new FcVenderImage();
        Date date = new Date();
        image.setCreateTime(date);
        image.setUpdateTime(date);
        try {
            String fileName = getImageName(file.getOriginalFilename());
            image.setWxCode(piggybankEndPoint+fileName);
            ossService.putObject(fileName,file.getBytes());
            image.setName(file.getOriginalFilename());
            fcVenderImageMapper.insert(image);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

    private String getImageName(String sourceName){
        StringBuffer sb = new StringBuffer();
        sb.append(UUID.randomUUID().toString());
        sb.append(sourceName.substring(sourceName.lastIndexOf(".")));
        return sb.toString();
    }

    /**
     * 将图片和业务id进行关联
     * @param vId
     * @param imageId
     */
    public void updateBiz(Integer vId, Integer imageId){
        FcVenderImage image = new FcVenderImage();
        image.setId(imageId);
        image.setVenderId(vId);
        fcVenderImageMapper.updateBiz(image);
    }

    public List<FcVenderImage> selectByType(FcVenderImage image){
        return fcVenderImageMapper.selectByType(image);
    }

    public void deleteById(Integer id){
        fcVenderImageMapper.deleteById(id);
    }
}
